package top.lushi78778.iot.mqtt.web.api.v1;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.onsmqtt20200420.models.SendMessageRequest;
import com.aliyun.onsmqtt20200420.models.SendMessageResponse;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.lushi78778.iot.mqtt.configurer.MqttConfigurer;
import top.lushi78778.iot.mqtt.core.MqttClient;
import top.lushi78778.iot.mqtt.core.Result;
import top.lushi78778.iot.mqtt.core.ResultGenerator;

/**
 * @ClassName Message
 * @Description 消息发送接口
 * @Author lushi
 * @Date 2021/7/7 21:44
 */
@RestController
@RequestMapping("/api/msg")
public class Message {
    /**
     * 向微消息队列 MQTT 版发送单条消息
     *
     * @param MqttTopic 将消息发往的微消息队列MQTT版的子Topic
     * @param Payload 消息内容，即消息负载。建议自行做Base64编码，避免传输不可见字符
     * @return MsgId 消息的唯一标识，RequestId 公共参数
     * @throws Exception 异常
     */
    @ApiOperation(value = "发送单条消息")
    @RequestMapping(value = "/send",method = {RequestMethod.POST})
    public Result<Object> SendMessage(@ApiParam(value = "子主题",required = true)@RequestParam String MqttTopic,
                                      @ApiParam(value = "消息内容，即消息负载，建议自行做Base64编码，避免传输不可见字符",required = true)@RequestParam String Payload) throws Exception {
        MqttConfigurer mqttConfigurer = new MqttConfigurer();
        mqttConfigurer.setSontopic(MqttTopic);
        com.aliyun.onsmqtt20200420.Client client = MqttClient.createClient(mqttConfigurer.getAccesskey(), mqttConfigurer.getSecretkey(), mqttConfigurer.getEndpoint());
        SendMessageRequest sendMessageRequest = new SendMessageRequest()
                .setMqttTopic(mqttConfigurer.getParenttopic()+"/"+mqttConfigurer.getSontopic())
                .setInstanceId(mqttConfigurer.getInstanceid())
                .setPayload(Payload);
        try {
            SendMessageResponse response = client.sendMessage(sendMessageRequest);
            JSONObject json = new JSONObject(response.toMap());
            String data = String.valueOf(json.getJSONObject("body"));
            return ResultGenerator.genSuccessResult(data);
        }catch (Exception exception){
            return ResultGenerator.genFailResult(exception.getMessage());
        }
    }
}